<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Qt Creator,">










<meta name="description" content="应用程序主窗口">
<meta name="keywords" content="Qt Creator">
<meta property="og:type" content="article">
<meta property="og:title" content="QtCreator学习（3）">
<meta property="og:url" content="http://Anzusen.com/2019/05/04/QtCreator学习（3）/index.html">
<meta property="og:site_name" content="Anzhusen">
<meta property="og:description" content="应用程序主窗口">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://anzusen.com/image/mainWindow_tree.png">
<meta property="og:image" content="http://anzusen.com/image/mainWindow_page.png">
<meta property="og:image" content="http://anzusen.com/image/mainWindow_result1.png">
<meta property="og:image" content="http://anzusen.com/image/QMdiArea_page.png">
<meta property="og:image" content="http://anzusen.com/image/Dock_page.png">
<meta property="og:image" content="http://anzusen.com/image/satus_page.png">
<meta property="og:updated_time" content="2020-04-06T13:16:00.583Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="QtCreator学习（3）">
<meta name="twitter:description" content="应用程序主窗口">
<meta name="twitter:image" content="http://anzusen.com/image/mainWindow_tree.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://Anzusen.com/2019/05/04/QtCreator学习（3）/">





  <title>QtCreator学习（3） | Anzhusen</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>
    <a href="https://github.com/ananzhusen/ananzhusen.github.io" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewbox="0 0 250 250" style="fill:#64CEAA; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"/><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"/><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"/></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Anzhusen</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://Anzusen.com/2019/05/04/QtCreator学习（3）/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="ananzhusen">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/touxiang.JPG">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Anzhusen">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">QtCreator学习（3）</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-05-04T09:27:31+08:00">
                2019-05-04
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/QT界面/" itemprop="url" rel="index">
                    <span itemprop="name">QT界面</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2019/05/04/QtCreator学习（3）/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/2019/05/04/QtCreator学习（3）/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv">本文总阅读量 <i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv"></span>次
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  5.1k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  19
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h3 id="应用程序主窗口"><a href="#应用程序主窗口" class="headerlink" title="应用程序主窗口"></a>应用程序主窗口</h3><a id="more"></a>
<p> 应用程序主窗口关系图：<br><img src="/image/mainWindow_tree.png" alt="主窗口关系图"></p>
<h4 id="主窗口框架"><a href="#主窗口框架" class="headerlink" title="主窗口框架"></a>主窗口框架</h4><p>  主窗口为建立应用程序用户界面提供了一个框架，Qt提供了QMainWindow和其他一些相关类共同完成主窗口的管理。QMainWindow类拥有自己的布局，包含以下部件：</p>
<ul>
<li>菜单栏(QMenuBar)。菜单栏包含了一个下拉菜单项的列表,这些菜单项由QAction动作类实现。菜单栏位于主窗口的顶部,一个主窗口只能有一个菜单栏。</li>
<li>工具栏(QToolBar)。工具栏一般用于显示一一些常用的菜单项目,也可以插入其他窗口部件,并且是可以移动的。一个主窗口可以拥有多个工具栏。</li>
<li>中心部件(Central Widget)。在主窗口的中心区域可以放入一个窗口部件作为中心部件,是应用程序的主要功能实现区域。一个主窗口只能拥有一个中心部件。</li>
<li>Dock部件(QDockWidget)。Dock 部件常被称为停靠窗口,因为可以停靠在中心部件的四周,用来放置- -些部件来实现- -些功能,就像个工具箱一样。一个主窗口可以拥有多个Dock部件。</li>
<li><p>状态栏(QStatusBar)。状态栏用于显示程序的一.些状态信息,在主窗口的最底部。一个主窗口只能拥有一个状态栏。<br><img src="/image/mainWindow_page.png" alt="主窗口界面布局"></p>
<p>本节知识可以在帮助索引中通过Application Main Window关键字查看。</p>
</li>
</ul>
<h5 id="Qt资源系统、菜单栏和工具栏"><a href="#Qt资源系统、菜单栏和工具栏" class="headerlink" title="Qt资源系统、菜单栏和工具栏"></a>Qt资源系统、菜单栏和工具栏</h5><p>  新建Qt Widgets应用,项目名称mymainwindow ,类名默认为MainWindow,基类默认为QMainWindow,不改动。建立好项目后,在文件列表中双击mainwindow. ui文件进人设计模式,这时在设计区域出现的便是主窗口界面。下面来添加菜单,双击左上角的“在这里输人”,修改为“文件(&amp;F)”,这里要使用英文半角的括号,“&amp;F”被称为加速键,表明程序运行时可以按下Alt+F键来激活该菜单。修改完成后按下回车键,并在弹出的下拉菜单中将第一项改为“新建文件(&amp;N)”,并按下回车键(由于版本原因，<strong>如果这里无法直接输人中文,则可以通过复制粘贴完成),</strong>这时可以看到，下面的Action编辑器中已经有了“新建文件”动作。选中该动作并将其拖入菜单栏下面的工具栏中。运行程序<br>  为菜单添加图标：</p>
<ol>
<li><strong>使用资源</strong><br> 这里将使用Qt的资源系统来存储图片,就可以嵌人到可执行文件之中了。避免图片位置发生变化,程序将无法显示图片这个问题。步骤如下:</li>
</ol>
<ul>
<li>添加Qt资源文件。往项目中添加新文件,选择Qt分类中的Qt ResourceFile,文件名称改为myimages,其他选项默认即可。</li>
<li>添加资源。建立好资源文件后会默认进人资源管理界面，打开myimages.qrc文件。现在先到项目文件夹mymainwindow中新建一个名为images的文件夹,并在其中放人两张图标图片,比如放人了一个new. png和一个open. png图片。(注意:Qt资源系统要求资源文件必须放在与qre文件同级或子级目录下，如果放在其他地方,则添加资源时会提示将文件复制到有效的位置。)</li>
<li>回到QtCreator中，在资源管理界面单击“添加”按钮,选择“添加前缀”,然后将属性栏中的前缀改为“/image”,再单击“添加”按钮选择添加文件”,在弹出的对话框中进人到前面新建的images文件夹中,选中那两张图片,单击“打开”即可。这时myimages. qre文件中就出现了添加的图片列表。最后,<strong>按下Ctrl+S快捷键保存对文件的修改</strong>(注意:这一点很重要,如果没有保存,下面使用图片时将看不到图片)。</li>
<li>使用图片。先使用Ctrl+ Tab快捷键转到mainwindow. ui文件.回到设计模式(如果先前没有打开过mainwindow. ui文件,那么该快捷键无法切换,需要直接双击该文件进行打开)。在Action编辑器中双击“新建文件”动作,这时会弹出编辑动作对话框。将对象名称改为action_New,工具提示ToolTip改为“新建文件”,然后按下“图标”后面的按钮进人选择资源界面。第一次进入该界面时,如果没有显示可用的资源,则可以单击左上角的重新加载绿色箭头图标 ,这时图片资源就显示出来了。这里选择new.png图片并单击OK按钮。最后在快捷键Shortcut后面的输入栏上单击并按下Ctrl+N组合键.就可以将它设为这个动作的快捷键了。这样就为动作添加了图标和快捷键,单击OK按钮关闭对话框。因为设置了工具提示，所以运行程序时可以将鼠标停在工具栏的一个动作上来显示提示信息。</li>
</ul>
<ol start="2">
<li><p>编写代码方式添加菜单<br> 下面使用代码来添加一个菜单,在mainwindow. cpp文件的MainWin-dow类构造函数中添加代码:</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">QMenu *editMenu=ui-&gt;menuBar-&gt;addMenu(tr(<span class="string">"编辑(&amp;E)"</span>));            <span class="comment">//添加编辑菜单</span></span><br><span class="line">QAction *action_Open=editMenu-&gt;addAction(</span><br><span class="line">            QIcon(<span class="string">":/image/images/open.png"</span>),tr(<span class="string">"打开文件(&amp;O)"</span>)); <span class="comment">//添加打开菜单</span></span><br><span class="line">QAction *action_Open2=editMenu-&gt;addAction(</span><br><span class="line">            QIcon(<span class="string">":/image/images/open.png"</span>),tr(<span class="string">"删除文件(&amp;D)"</span>));</span><br><span class="line">action_Open-&gt;setShortcut(QKeySequence(<span class="string">"ctrl+O"</span>));                <span class="comment">//设置快捷键</span></span><br><span class="line">ui-&gt;mainToolBar-&gt;addAction(action_Open);    <span class="comment">//在工具栏中添加动作</span></span><br><span class="line">ui-&gt;mainToolBar-&gt;addAction(action_Open2);</span><br></pre></td></tr></table></figure>
<p>这里使用ui→menuBar来获取QMainWindow的菜单栏,使用ui→mainToolBar来获取QMainWindow的工具栏,然后分别使用相应的函数添加菜单和动作</p>
</li>
<li>菜单栏<br> QMenu中还提供了间隔器.可以在设计器中向添加菜单那样直接添加间隔器,或者在代码中使用addSeparator()函数来添加,它是一条水平线，可以将菜单进行分组,使得布局很整齐。应用程序中很多普通的命令都是通过菜单来实现的，而我们也希望能将这些菜单命令放到工具栏中以方便使用。QAction 就是这样一种命令动作，可以同时放在菜单和工具栏中。一个QAction动作包含了图标、菜单显示文本、快捷键、状态栏显示文本、“What’s This?”显示文本和工具提示文本。这些都可以在构建QAction类对象时在构造函数中指定。另外,还可以设置QAction的checkable属性,如果指定这个动作的checkable为true,那么选中这个菜单时就会在它的前面显示小圆点之类的表示选中状态的符号;如果该菜单有图标.就会用线框将图标围住.用来表示该动作被选中了。<br> 下面再介绍一个动作组QActionGroup类。它可以包含一组动作QAction,可以设置这组动作中是否<strong>只能有一个动作处于选中状态</strong>,这对于互斥型动作很有用。在前面程序的MainWindow类构造函数中继续添加如下代码:</li>
</ol>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">QActionGroup *group=<span class="keyword">new</span> QActionGroup(<span class="keyword">this</span>);           <span class="comment">//建立动作组</span></span><br><span class="line">QAction *action_L=group-&gt;addAction(tr(<span class="string">"左对齐(&amp;L)"</span>));  <span class="comment">//向动作组中添加动作</span></span><br><span class="line">action_L-&gt;setCheckable(<span class="literal">true</span>);                         <span class="comment">//设置动作有选中和未选中状态</span></span><br><span class="line">QAction *action_R=group-&gt;addAction(tr(<span class="string">"右对齐(&amp;R)"</span>));</span><br><span class="line">action_R-&gt;setCheckable(<span class="literal">true</span>);</span><br><span class="line">QAction *action_C=group-&gt;addAction(tr(<span class="string">"居中对齐(&amp;C)"</span>));</span><br><span class="line">action_C-&gt;setCheckable(<span class="literal">true</span>);</span><br><span class="line">action_L-&gt;setChecked(<span class="literal">true</span>);         <span class="comment">//指定初始action_L为默认选中状态</span></span><br><span class="line">editMenu-&gt;addSeparator();           <span class="comment">//向菜单中添加间隔器</span></span><br><span class="line">editMenu-&gt;addAction(action_L);      <span class="comment">//向编辑菜单中添加动作</span></span><br><span class="line">editMenu-&gt;addAction(action_R);</span><br><span class="line">editMenu-&gt;addAction(action_C);</span><br></pre></td></tr></table></figure>
<ol start="4">
<li>工具栏<br> 工具栏QToolBar类提供了一-个包含了一组控件的、可以移动的面板。前面已经看到可以将QAction对象添加到工具栏中,默认只是显示一个动作的图标，可以在QToolBar的属性栏中进行更改。在设计器中查看QToolBar的属性栏：</li>
</ol>
<ul>
<li>toolButtonStyle属性用来设置图标和相应文本的显示及其相对位置;</li>
<li>movabel属性用来设置状态栏是否可以移动;</li>
<li>allowedArea用来设置允许停靠的位置;</li>
<li>iconsize属性用来设置图标的大小;</li>
<li><p>floatable属性用来设置是否可以悬浮。</p>
<p>工具栏中除了可以添加<strong>动作</strong>外,还可以添加其他的<strong>窗口部件</strong>,下面在前面的程序中的mainwindow.cpp文件中添加头文件:</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;QToolButton&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;QSpinBox&gt;</span></span></span><br></pre></td></tr></table></figure>
<p>在构造函数中继续添加代码</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">QToolButton *toolBtn=<span class="keyword">new</span> QToolButton(<span class="keyword">this</span>); <span class="comment">//创建QToolButton</span></span><br><span class="line">toolBtn-&gt;setText(tr(<span class="string">"颜色"</span>));</span><br><span class="line">QMenu *colorMenu=<span class="keyword">new</span> QMenu(<span class="keyword">this</span>);           <span class="comment">//创建一个颜色菜单</span></span><br><span class="line">colorMenu-&gt;addAction(tr(<span class="string">"红色"</span>));</span><br><span class="line">colorMenu-&gt;addAction(tr(<span class="string">"绿色"</span>));</span><br><span class="line">toolBtn-&gt;setMenu(colorMenu);                <span class="comment">//为工具栏添加菜单</span></span><br><span class="line">toolBtn-&gt;setPopupMode(QToolButton::MenuButtonPopup); <span class="comment">//设置弹出模式</span></span><br><span class="line">ui-&gt;mainToolBar-&gt;addWidget(toolBtn);   <span class="comment">//向工具栏中添加QToolButton按钮</span></span><br><span class="line">QSpinBox *spinBox=<span class="keyword">new</span> QSpinBox(<span class="keyword">this</span>);  <span class="comment">//创建QSpinBox</span></span><br><span class="line">ui-&gt;mainToolBar-&gt;addWidget(spinBox);   <span class="comment">//向工具栏中添加QSpinBox部件</span></span><br></pre></td></tr></table></figure>
<p>这里创建了一个QToolButton类对象,并为它添加了一个弹出菜单,设置了弹出方式是在按钮旁边有一个向下的小箭头,可以按下这个箭头弹出菜单(默认的弹出方式是按下按钮一段时间才弹出菜单)。最后将它添加到了工具栏中。下面又在工具栏中添加了一个QSpinBox部件,可以看到，往工具栏中添加部件可以使用addWidget()函数。</p>
<p>这里还要再说明一下QToolButton类。其实,当往工具栏中添加一个QAction类对象时就会自动创建了一个QToolButton实例，所以说工具栏上的动作就是一个QToolButton,这就是属性栏中会有toolButtonStyle的原因。</p>
</li>
</ul>
<p>以上运行结果如图所示：<br><img src="/image/mainWindow_result1.png" alt="主窗口界面布局运行结果"></p>
<h5 id="中心部件"><a href="#中心部件" class="headerlink" title="中心部件"></a>中心部件</h5><p>  主窗口的中心区域可以放置一个中心部件,它一般是一个编辑器或者浏览器。这里支持单文档部件,也支持多文档部件。一般的，我们会在这里放置一个部件,然后使用布局管理器使其充满整个中心区域，并可以随着窗口的大小变化而变化。下面在前面的程序中添加中心部件。在设计模式中,往中心区域拖人一个Text Edit,然后单击界面,按下Ctrl+G,使其处于一个栅格布局中。现在可以运行程序查看效果。</p>
<ul>
<li>QTextEdit是一个高级的WYSIWYG(所见即所得)浏览器和编辑器，支持富文本的处理,为用户提供了强大的文本编辑功能。</li>
<li>与QTextEdit对应的是QPlainTextEdit类,它提供了一个纯文本编辑器,这个类与QTextEdit类的很多功能都很相似,只不过无法处理富文本。</li>
<li>还有一个QTextBrowser类,它是一一个富文本浏览器,可以看作是QTextE-dit的只读模式。</li>
<li><p>这3个类的用法大同小异。</p>
<p>中心区域还可以使用多文档部件。Qt中的QMdiArea部件就是用来提供一个可以显示MDI( Multiple Document Interface)多文档界面的区域,从而有效地管理多个窗口。QMdiArea中的子窗口由QMdiSubWindow类提供,这个类有自己的布局,包含一个标题栏和一个中心区域,可以向它的中心区域添加部件。</p>
<p>下面更改前面的程序,在设计模式将前面添加的TextEdit部件删除，然后拖入一个MDI Area部件。在Action编辑器中的“新建文件”动作上右击,在弹出的级联菜单中选择“转到槽”,然后在弹出的对话框中选择triggered()触发信号,单击OK按钮后便转到mainwindow. cpp文件中的该信号的槽的定义处,更改如下:</p>
</li>
</ul>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">void</span> MainWindow::on_action_New_triggered()</span><br><span class="line">&#123;</span><br><span class="line">    <span class="comment">//新建文本编辑器</span></span><br><span class="line">    QTextEdit *edit=<span class="keyword">new</span> QTextEdit(<span class="keyword">this</span>);</span><br><span class="line">    <span class="comment">//使用QMdiArea类的addSubWindow()函数创建子窗口，以文本编辑器为中心部件。</span></span><br><span class="line">    QMdiSubWindow *child=ui-&gt;mdiArea-&gt;addSubWindow(edit);</span><br><span class="line">    child-&gt;setWindowTitle(tr(<span class="string">"多文档编辑器子窗口"</span>));</span><br><span class="line">    child-&gt;show();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>  这里需要先添加井include &lt; QTextEdit&gt;和井include &lt; QMdiSubWindow&gt;头文件在新建文件菜单动作的触发信号槽on_action_New_trigered()中创建了多文档区域的子窗口。这时运行程序,然后按下工具栏上的新建文件动作图标,每按下一次，就会生成一个子窗口,如图所示。</p>
<p><img src="/image/QMdiArea_page.png" alt="中心部件运行结果"></p>
<h5 id="Dock部件"><a href="#Dock部件" class="headerlink" title="Dock部件"></a>Dock部件</h5><p>  QDockWidget类提供了这样一个部件,可以停靠在QMainWindow中,也可以悬浮起来作为桌面顶级窗口,称为Dock部件或者停靠窗口。Dock部件一般用于存放一些其他部件来实现特殊功能,就像一个工具箱。在主窗口中可以停靠在中心部件的四周，也可以悬浮起来被拖动到任意的地方,还可以被关闭或隐藏起来。一个Dock部件包含一个标题栏和一个内容区域,可以向Dock部件中放人任何部件。</p>
<p>  在设计模式中向中心区域拖入一个Dock Widget 部件,然后再向Dock中随意拖人几个部件,比如这里拖入一个Push Button和一个Font Combo Box。在dock Widget的属性栏中更改其windowTitle为“工具箱”,另外还可以设置它的features属性,包含是否可以关闭、移动和悬浮等;还有allowedArea属性,用来设置可以停靠的区域。</p>
<p>  下面在文件菜单中添加“显示Dock” 菜单项,然后在Action 编辑器中转到“显示Dock”动作的触发信号triggered()的槽函数,更改如下:<br><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">void</span> MainWindow::on_action_Dock_triggered()</span><br><span class="line">&#123;</span><br><span class="line">    ui-&gt;dockWidget-&gt;show();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>运行程序，关闭Dock部件后，按下显示Dock这个菜单项，就可以从新显示Dock了，运行结果如图：</p>
<p><img src="/image/Dock_page.png" alt="停靠窗口工具箱运行结果"></p>
<h5 id="状态栏"><a href="#状态栏" class="headerlink" title="状态栏"></a>状态栏</h5><p>  QStatusBar类提供了一个<strong>水平条部件</strong>,用来显示状态信息。QMainWindow 中默认提供了一个状态栏。状态信息可以被分为3类:</p>
<ul>
<li>临时信息,如一般的提示信息;</li>
<li>正常信息,如显示页数和行号;</li>
<li>永久信息，如显示版本号或者日期。</li>
</ul>
<p>显示函数：</p>
<ul>
<li>使用showMessage()函数显示一个临时消息,它会出现在状态栏的最左边。</li>
<li>用addWidget()函数添加一个QLabel到状态栏上,用于显示正常信息,它会生成到状态栏的最左边,可能被临时消息掩盖。</li>
<li><p>显示永久信息，则要使用addPermanentWidget()函数来添加一.个如QLabel–样的可以显示信息的部件,它会生成在状态栏的最右端,不会被临时消息掩盖。</p>
<p>状态栏的最右端还有一个QSizeGrip部件,用来调整窗口的大小，可以使用set-SizeGripEnabled()函数来禁用它。<br>因为目前的设计器还不支持直接向状态栏中拖放部件,所以需要使用代码来生成。向mainwindow.cpp文件中的构造函数里继续添加代码:</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;QLabel&gt;</span></span></span><br><span class="line">   <span class="comment">//显示临时消息，时长为20000毫秒</span></span><br><span class="line">   ui-&gt;statusBar-&gt;showMessage(tr(<span class="string">"欢迎使用多文档编辑器"</span>),<span class="number">20000</span>);</span><br><span class="line">   <span class="comment">//创建标签，设置标签样式和显示信息，将其以永久部件形式添加到状态栏</span></span><br><span class="line">   QLabel *permanent=<span class="keyword">new</span> QLabel(<span class="keyword">this</span>);</span><br><span class="line">   permanent-&gt;setFrameStyle(QFrame::Box|QFrame::Sunken);</span><br><span class="line">   permanent-&gt;setText(<span class="string">"www.qter.org"</span>);</span><br><span class="line">   ui-&gt;statusBar-&gt;addPermanentWidget(permanent);</span><br></pre></td></tr></table></figure>
<p>此时运行程序可以发现“欢迎使用多文档编辑器”字符串在显示一会儿后就自动消失了,而“www. qter. org”一直显示在状态栏最右端。如图所示：<br><img src="/image/satus_page.png" alt="状态栏运行结果"></p>
</li>
</ul>
<h5 id="自定义菜单"><a href="#自定义菜单" class="headerlink" title="自定义菜单"></a>自定义菜单</h5><p>  Qt中的QWidgetAction类就提供了在菜单中使用其他部件功能。为了实现自定义菜单,需要新建一个类，它继承自QWidgetAction 类,并且在其中重新实现create-Widget()函数。下面的例子中实现了这样一个菜单项:包含一个标签和一个行编辑器,可以在行编辑器中输人字符串,按下回车键就可以自动将字符串输入到中心部件文本编辑器中。<br>  新建Qt Widgets应用,项目名称为myaction,类名默认为MainWindow ,基类默认为QMainWindow不改动。建好项目后往项目中添加新文件模板选择C++ Class, 类名设置为MyAction,基类设置为QWidgetAction。</p>
<ol>
<li><p>myaction.h中添加代码：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">ifndef</span> MYACTION_H</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> MYACTION_H</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;QWidgetAction&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">QLineEdit</span>;</span>    <span class="comment">//前置声明</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyAction</span> :</span> <span class="keyword">public</span> QWidgetAction</span><br><span class="line">&#123;</span><br><span class="line">    Q_OBJECT</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    <span class="function"><span class="keyword">explicit</span> <span class="title">MyAction</span><span class="params">(QObject *parent=<span class="number">0</span>)</span></span>;</span><br><span class="line"><span class="keyword">protected</span>:</span><br><span class="line">    <span class="comment">//声明函数，该函数是QWidgetAction类中的虚函数</span></span><br><span class="line">    <span class="function">QWidget *<span class="title">createWidget</span><span class="params">(QWidget *parent)</span></span>;</span><br><span class="line">signals:</span><br><span class="line">    <span class="comment">//新建信号，用于在按下回车键时，将行编辑器中的内容发射出去</span></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">getText</span><span class="params">(<span class="keyword">const</span> QString &amp;<span class="built_in">string</span>)</span></span>;</span><br><span class="line"><span class="keyword">private</span> slots:</span><br><span class="line">    <span class="comment">//新建槽，它用来与行编辑器的按下回车键信号关联</span></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">sendText</span><span class="params">()</span></span>;</span><br><span class="line"><span class="keyword">private</span>:</span><br><span class="line">    <span class="comment">//声明行编辑器对象的指针</span></span><br><span class="line">    QLineEdit *lineEdit;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="meta-keyword">endif</span> <span class="comment">// MYACTION_H</span></span></span><br></pre></td></tr></table></figure>
</li>
<li><p>myaction.cpp中添加代码：</p>
</li>
</ol>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">"myaction.h"</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;QLineEdit&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;QSplitter&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;QLabel&gt;</span></span></span><br><span class="line"></span><br><span class="line">MyAction::MyAction(QObject *parent):</span><br><span class="line">    QWidgetAction(parent)</span><br><span class="line">&#123;</span><br><span class="line">    <span class="comment">//创建行编辑器</span></span><br><span class="line">    lineEdit=<span class="keyword">new</span> QLineEdit;</span><br><span class="line">    <span class="comment">//将行编辑器按下回车键信号与发送文本槽关联</span></span><br><span class="line">    connect(lineEdit,&amp;QLineEdit::returnPressed,<span class="keyword">this</span>,&amp;MyAction::sendText);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">QWidget *MyAction::createWidget(QWidget *parent)</span><br><span class="line">&#123;</span><br><span class="line">    <span class="comment">//这里使用inherits()函数判断父部件（是否继承）是否是菜单或工具栏</span></span><br><span class="line">    <span class="comment">//如果是，则创建该父部件的子部件，并返回子部件</span></span><br><span class="line">    <span class="comment">//如果不是，则直接返回0</span></span><br><span class="line">    <span class="keyword">if</span>(parent-&gt;inherits(<span class="string">"QMenu"</span>)||parent-&gt;inherits(<span class="string">"QToolBar"</span>))&#123;</span><br><span class="line">        QSplitter *splitter = <span class="keyword">new</span> QSplitter(parent);<span class="comment">// 创建分裂器</span></span><br><span class="line">        QLabel *label=<span class="keyword">new</span> QLabel;</span><br><span class="line">        label-&gt;setText(tr(<span class="string">"插入文本："</span>));</span><br><span class="line">        splitter-&gt;addWidget(label);</span><br><span class="line">        splitter-&gt;addWidget(lineEdit);</span><br><span class="line">        <span class="keyword">return</span> splitter;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">void</span> MyAction::sendText()</span><br><span class="line">&#123;</span><br><span class="line">    <span class="function">emit <span class="title">getText</span><span class="params">(lineEdit-&gt;text())</span></span>;<span class="comment">//发射信号，将行编辑器中的内容发射出去</span></span><br><span class="line">    lineEdit-&gt;clear();             <span class="comment">//清空行编辑器中的内容</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ol start="3">
<li>双击mainwindow.ui文件进入设计模式，向中心区域拖入一个Text Edit部件，并使用ctrl+G使其处于一个栅格布局中。</li>
<li><p>在mainwindow.h中添加代码：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">ifndef</span> MAINWINDOW_H</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> MAINWINDOW_H</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;QMainWindow&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="keyword">namespace</span> Ui &#123;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MainWindow</span>;</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MainWindow</span> :</span> <span class="keyword">public</span> QMainWindow</span><br><span class="line">&#123;</span><br><span class="line">    Q_OBJECT</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    <span class="function"><span class="keyword">explicit</span> <span class="title">MainWindow</span><span class="params">(QWidget *parent = <span class="number">0</span>)</span></span>;</span><br><span class="line">    ~MainWindow();</span><br><span class="line"></span><br><span class="line"><span class="keyword">private</span>:</span><br><span class="line">    Ui::MainWindow *ui;</span><br><span class="line"><span class="keyword">private</span> slots:</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">setText</span><span class="params">(<span class="keyword">const</span> QString &amp;<span class="built_in">string</span>)</span></span>;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="meta-keyword">endif</span> <span class="comment">// MAINWINDOW_H</span></span></span><br></pre></td></tr></table></figure>
</li>
<li><p>在mainwindow.cpp中添加代码：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">"mainwindow.h"</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">"ui_mainwindow.h"</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">"myaction.h"</span></span></span><br><span class="line"></span><br><span class="line">MainWindow::MainWindow(QWidget *parent) :</span><br><span class="line">    QMainWindow(parent),</span><br><span class="line">    ui(<span class="keyword">new</span> Ui::MainWindow)</span><br><span class="line">&#123;</span><br><span class="line">    ui-&gt;setupUi(<span class="keyword">this</span>);</span><br><span class="line">    MyAction *action =<span class="keyword">new</span> MyAction;</span><br><span class="line">    QMenu *editMenu=ui-&gt;menuBar-&gt;addMenu(tr(<span class="string">"编辑(&amp;E)"</span>));</span><br><span class="line">    editMenu-&gt;addAction(action);</span><br><span class="line">    connect(action,SIGNAL(getText(QString)),<span class="keyword">this</span>,SLOT(setText(QString)));</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">MainWindow::~MainWindow()</span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">delete</span> ui;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">void</span> MainWindow::setText(<span class="keyword">const</span> QString &amp;<span class="built_in">string</span>)</span><br><span class="line">&#123;</span><br><span class="line">    ui-&gt;textEdit-&gt;setText(<span class="built_in">string</span>);<span class="comment">//将获取的文本添加到编辑器中</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>现在运行程序,在编辑菜单中单击自定义的菜单动作,然后输人字符并按下回车键,可以看到输人的字符自动添加到了文本编辑器中。<br>这个例子中设计了自己的信号和槽，整个过程是这样的:在行编辑器中输人文本，然后按下回车键,这时行编辑就会发射returnPressed()信号,而这时就调用了我们的sendText()槽,在sendText()槽中又发射了getText()信号,信号中包含了行编辑器中的文本,接着又会调用setText()槽,在setText()槽中将getText()信号发来的文本输人到文本编辑器中。这样就完成了按下回车键将行编辑器中的文本输人到中心部件的文本编辑器中的操作。</p>
</li>
</ol>
<h4 id="富文本处理"><a href="#富文本处理" class="headerlink" title="富文本处理"></a>富文本处理</h4><p>  富文本(Rich Text)或者叫富文本格式,简单来说就是在文档中可以使用多种格式,比如字体颜色、图片和表格等。它是与纯文本(Plain Text)相对而言的，比如Windows.上的记事本就是纯文本编辑器,而Word就是富文本编辑器。Qt中提供了对富文本处理的支持,可以在帮助中通过Rich Text Processing关键字查看。</p>
<h5 id="富文本文档结构"><a href="#富文本文档结构" class="headerlink" title="富文本文档结构"></a>富文本文档结构</h5><p>富文本处理：</p>
<ul>
<li>编辑操作-&gt;基于光标的一些接口函数-&gt;textCursor()函数-&gt;基于QTextCursor类<ul>
<li>QTextFrameFormat</li>
<li>QTextBlockFormat</li>
<li>QTextTableFormat</li>
<li>QTextListFormat</li>
</ul>
</li>
<li>只读操作-&gt;基于文档结构，使用了只读的分层次的接口函数-&gt;document()函数-&gt;基于QTextDocument类<ul>
<li>QTextFrame</li>
<li>QTextBlock</li>
<li>QTextTable</li>
<li>QTextList<h5 id="文本块"><a href="#文本块" class="headerlink" title="文本块"></a>文本块</h5><h5 id="表格、列表与图片"><a href="#表格、列表与图片" class="headerlink" title="表格、列表与图片"></a>表格、列表与图片</h5><h5 id="查找功能"><a href="#查找功能" class="headerlink" title="查找功能"></a>查找功能</h5><h5 id="语法高亮与HTML"><a href="#语法高亮与HTML" class="headerlink" title="语法高亮与HTML"></a>语法高亮与HTML</h5></li>
</ul>
</li>
</ul>
<h4 id="拖放操作"><a href="#拖放操作" class="headerlink" title="拖放操作"></a>拖放操作</h4><h5 id="使用拖放打开文件"><a href="#使用拖放打开文件" class="headerlink" title="使用拖放打开文件"></a>使用拖放打开文件</h5><h5 id="自定义拖放操作"><a href="#自定义拖放操作" class="headerlink" title="自定义拖放操作"></a>自定义拖放操作</h5><h4 id="打印文档"><a href="#打印文档" class="headerlink" title="打印文档"></a>打印文档</h4><p>为什么后面没内容了呢？发现看电子档太无聊了啊，然后开始看视频了。。。。</p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>你可以对我进行打赏哦</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/weichat.jpg" alt="ananzhusen 微信支付">
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.jpg" alt="ananzhusen 支付宝">
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Qt-Creator/" rel="tag"># Qt Creator</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/05/02/QtCreator学习（2）/" rel="next" title="QtCreator学习（2）">
                <i class="fa fa-chevron-left"></i> QtCreator学习（2）
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/05/06/Qt实战（1）/" rel="prev" title="Qt实战（1）">
                Qt实战（1） <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        <!-- JiaThis Button BEGIN -->
<div class="jiathis_style">
<span class="jiathis_txt">分享到：</span>
<a class="jiathis_button_fav">收藏夹</a>
<a class="jiathis_button_copy">复制网址</a>
<a class="jiathis_button_email">邮件</a>
<a class="jiathis_button_weixin">微信</a>
<a class="jiathis_button_qzone">QQ空间</a>
<a class="jiathis_button_tqq">腾讯微博</a>
<a class="jiathis_button_douban">豆瓣</a>
<a class="jiathis_button_share">一键分享</a>

<a href="http://www.jiathis.com/share?uid=2140465" class="jiathis jiathis_txt jiathis_separator jtico jtico_jiathis" target="_blank">更多</a>
<a class="jiathis_counter_style"></a>
</div>
<script type="text/javascript">
var jiathis_config={
  data_track_clickback:true,
  summary:"",
  shortUrl:false,
  hideMore:false
}
</script>
<script type="text/javascript" src="http://v3.jiathis.com/code/jia.js?uid=" charset="utf-8"></script>
<!-- JiaThis Button END -->
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/touxiang.JPG" alt="ananzhusen">
            
              <p class="site-author-name" itemprop="name">ananzhusen</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">23</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">13</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">43</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/ananzhusen" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://weibo.com/5817162963" target="_blank" title="weibo">
                      
                        <i class="fa fa-fw fa-weibo"></i>weibo</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-block">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                Links
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://gitee.com/anzhusen/" title="gitee" target="_blank">gitee</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#应用程序主窗口"><span class="nav-number">1.</span> <span class="nav-text">应用程序主窗口</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#主窗口框架"><span class="nav-number">1.1.</span> <span class="nav-text">主窗口框架</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#Qt资源系统、菜单栏和工具栏"><span class="nav-number">1.1.1.</span> <span class="nav-text">Qt资源系统、菜单栏和工具栏</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#中心部件"><span class="nav-number">1.1.2.</span> <span class="nav-text">中心部件</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#Dock部件"><span class="nav-number">1.1.3.</span> <span class="nav-text">Dock部件</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#状态栏"><span class="nav-number">1.1.4.</span> <span class="nav-text">状态栏</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#自定义菜单"><span class="nav-number">1.1.5.</span> <span class="nav-text">自定义菜单</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#富文本处理"><span class="nav-number">1.2.</span> <span class="nav-text">富文本处理</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#富文本文档结构"><span class="nav-number">1.2.1.</span> <span class="nav-text">富文本文档结构</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#文本块"><span class="nav-number">1.2.2.</span> <span class="nav-text">文本块</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#表格、列表与图片"><span class="nav-number">1.2.3.</span> <span class="nav-text">表格、列表与图片</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#查找功能"><span class="nav-number">1.2.4.</span> <span class="nav-text">查找功能</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#语法高亮与HTML"><span class="nav-number">1.2.5.</span> <span class="nav-text">语法高亮与HTML</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#拖放操作"><span class="nav-number">1.3.</span> <span class="nav-text">拖放操作</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#使用拖放打开文件"><span class="nav-number">1.3.1.</span> <span class="nav-text">使用拖放打开文件</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#自定义拖放操作"><span class="nav-number">1.3.2.</span> <span class="nav-text">自定义拖放操作</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#打印文档"><span class="nav-number">1.4.</span> <span class="nav-text">打印文档</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">ananzhusen</span>

  
</div>

<!-- 
  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>
 -->



        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      本站访客数 <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人次
    </span>
  

  
    <span class="site-pv">
      本站访问总量 <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  










  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item=>{
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: false,
        notify: false,
        appId: 'e69lyQSoCtoaLGljT3kXLBEQ-gzGzoHsz',
        appKey: 'pRDcFfyQnO4jQWxElUFupJ2D',
        placeholder: 'Just go go',
        avatar:'mm',
        guest_info:guest,
        pageSize:'10' || 10,
    });
  </script>



  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  


  
   <canvas class="fireworks" style="position: fixed;left: 0;top: 0;z-index: 1; pointer-events: none;"></canvas> 
   <script type="text/javascript" src="//cdn.bootcss.com/animejs/2.2.0/anime.min.js"></script> 
   <script type="text/javascript" src="/js/src/fireworks.js"></script>
  

</body>
</html>
